import time
import random
import numpy as np
from flask import Flask, render_template
from flask_socketio import SocketIO
from threading import Thread, Lock
import time

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app, async_mode='threading')

# 配置参数
SAMPLE_RATE = 1000  # 采样率 1000Hz
BUFFER_DURATION = 600  # 10分钟数据缓冲区
BUFFER_SIZE = BUFFER_DURATION * SAMPLE_RATE

# 数据缓冲区
class DataBuffer:
    def __init__(self):
        self.buffer = np.zeros((BUFFER_SIZE, 2), dtype=np.uint16)
        self.current_index = 0
        self.full = False
        self.lock = Lock()
        
        # 初始化填充随机数据
        for i in range(BUFFER_SIZE):
            self.add_sample((random.randint(0, 65535), random.randint(0, 65535)))
    
    def add_sample(self, sample):
        """添加新的采样点"""
        with self.lock:
            self.buffer[self.current_index] = sample
            self.current_index = (self.current_index + 1) % BUFFER_SIZE
            if self.current_index == 0:
                self.full = True
    
    def get_data_range(self, start_time, end_time, max_points=2000):
        """获取指定时间范围内的数据（降采样）"""
        with self.lock:
            # 计算起始和结束索引
            current_time = time.time()
            buffer_start_time = current_time - (BUFFER_SIZE / SAMPLE_RATE)
            
            # 确保请求的时间在缓冲区范围内
            start_time = max(start_time, buffer_start_time)
            end_time = min(end_time, current_time)
            
            # 计算索引位置
            start_idx = int((start_time - buffer_start_time) * SAMPLE_RATE)
            end_idx = int((end_time - buffer_start_time) * SAMPLE_RATE)
            
            # 获取数据切片
            if self.full:
                # 环形缓冲区已满
                if start_idx < self.current_index:
                    data_chunk = np.concatenate((
                        self.buffer[start_idx:min(end_idx, BUFFER_SIZE)],
                        self.buffer[:max(0, end_idx - BUFFER_SIZE)]
                    ))
                else:
                    data_chunk = self.buffer[start_idx - BUFFER_SIZE:end_idx - BUFFER_SIZE]
            else:
                # 缓冲区未满
                data_chunk = self.buffer[start_idx:min(end_idx, self.current_index)]
            
            # 降采样
            if len(data_chunk) > max_points:
                step = max(1, len(data_chunk) // max_points)
                data_chunk = data_chunk[::step]
            
            return data_chunk.tolist()

# 创建数据缓冲区
data_buffer = DataBuffer()

# 模拟数据接收线程
def data_generator():
    """模拟从网络接收数据"""
    while True:
        # 模拟接收1000个采样点（实际应用中替换为真实数据接收）
        for _ in range(1000):
            ch1 = random.randint(0, 65535)
            ch2 = random.randint(0, 65535)
            data_buffer.add_sample((ch1, ch2))
            
            # 发送实时数据点
            socketio.emit('new_data_point', {'ch1': ch1, 'ch2': ch2})
        
        time.sleep(1)  # 每秒添加1000个点

# WebSocket连接处理
@socketio.on('connect')
def handle_connect():
    print('客户端已连接')
    # 发送初始数据
    current_time = time.time()
    start_time = current_time - BUFFER_DURATION
    data = data_buffer.get_data_range(start_time, current_time)
    socketio.emit('initial_data', {
        'data': data,
        'time_range': [start_time, current_time]
    })

@app.route('/')
def index():
    return render_template('index.html')

if __name__ == '__main__':
    # 启动数据生成线程
    Thread(target=data_generator, daemon=True).start()
    socketio.run(app, host='0.0.0.0', port=5000)